package com.lambda.lambda.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * java8内置四大核心函数式接口
 * <p>
 * Consumer<T>：消费性接口
 * void accept(T t);
 * <p>
 * Supplier<T>:供给型接口
 * T get();
 * <p>
 * Function<T,R>:函数型接口
 * R apply(T);
 * <p>
 * Predicate<T>:断言型接口
 * boolean test(T);
 */
public class TestLambda2 {
    //Consumer<T>
    @Test
    public void test1() {
        happy(1.5, money -> System.out.println(money - 1));
    }

    public void happy(double money, Consumer<Double> co) {
        co.accept(money);
    }

    //Supplier<T>
    @Test
    public void test2() {
        List<Integer> list = getNumList(10, () -> (int) (Math.random() * 100));
        for (Integer integer : list) {
            System.out.println(integer);

        }
    }

    public List<Integer> getNumList(int num, Supplier<Integer> sup){
        List<Integer> list= new ArrayList<>();
        for(int i=0;i<num;i++) {
            Integer n = sup.get();
            list.add(n);
        }
        return list;
    }

    //Function<T,R>:
    @Test
    public void test3() {
        System.out.println(deal("aaa", x -> x.toUpperCase()));
    }

    public String deal(String a, Function<String,String > fu){
        return fu.apply(a);
    }

    //Predicate<T>
    List<String> list= Arrays.asList("aa","b","ccc");

    @Test
    public void test4() {
        List<String> filter = filter(list, pre -> pre.length() > 1);
        for (String s : filter) {
            System.out.println(s);
        }
    }
    public List<String> filter(List<String> list, Predicate<String> pre){
        List<String> str = new ArrayList<>();
        for (String s : list) {
            if(pre.test(s)){
                str.add(s);
            }
        }
        return str;
    }
}
